package cn.gbase.jiangsu.data.transfer.service;

import java.util.ArrayList;
import java.util.List;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.service.IdEntityService;

import cn.gbase.jiangsu.data.transfer.bean.SupplierUser;
import cn.gbase.jiangsu.data.transfer.bean.SystemUser;
import cn.gbase.jiangsu.data.transfer.common.Constants;
import cn.gbase.jiangsu.data.transfer.util.DefaultPasswordEncoder;

@IocBean(args = { "refer:dao" })
public class SupplierUserService extends IdEntityService<SupplierUser> {

	public SupplierUserService() {
		super();
	}

	public SupplierUserService(Dao dao) {
		super(dao);
	}

	/**
	 * 更新密码.
	 * 
	 * @param user
	 * @return
	 */
	public void updatePWS(SupplierUser user) {

		// 密码加密
		String encodePass = new DefaultPasswordEncoder("MD5").encode(user
				.getNewPassword());

		// 更新
		this.dao().update(SupplierUser.class, Chain.make("pw", encodePass),
				Cnd.where("id", "=", user.getId()));
	}
	/**
	 * 取得用户列表.
	 * 
	 * @param pageNumber
	 * @param username
	 * @param realname
	 * @return
	 */
	public QueryResult getUserList(int pageNumber, String username,
			String realname,int sid,int uid) {

		if (pageNumber <= 0) {
			pageNumber = 1;
		}

		// 拼接条件
		SqlExpressionGroup group = Cnd.exps("1", "=", 1);
		if (username != null && username.length() > 0) {
			group = group.and("username", "like", "%" + username + "%");
		}
		if (realname != null && realname.length() > 0) {
			group = group.and("remark", "like", "%" + realname + "%");
		}
		group = group.and("supplierId", "=", sid); //供应商ID
		group = group.and("status", "<>", 0); //不是被删除的
		group = group.and("id", "<>", uid); //去除登录人ID
		// 最大页数
		Pager pager = this.dao().createPager(pageNumber,
				Constants.LIST_ONE_PAGE_SIZE);

		// 查询记录总数
		int recordCount = this.dao()
				.count(SupplierUser.class, Cnd.where(group));
		pager.setRecordCount(recordCount);

		// 没数据，直接返回
		if (recordCount == 0) {
			return new QueryResult(new ArrayList<SupplierUser>(0), pager);
		}

		// 计算页数
		int maxPageNumber = 0;
		if (recordCount % Constants.LIST_ONE_PAGE_SIZE == 0) {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE;
		} else {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE + 1;
		}
		if (pageNumber > maxPageNumber) {
			pager.setPageNumber(maxPageNumber);
		}

		// 查询
		List<SupplierUser> resultList = this.dao().query(SupplierUser.class,
				Cnd.where(group).desc("id"), pager); // 当前页面显示记录

		// 返回
		return new QueryResult(resultList, pager);

	}
}
